package com.ywjh.inter.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.ywjh.inter.entity.InsulinPenGlucoseEntity;
import com.ywjh.inter.utils.DateUtil;

public class InsulinPenGlucoseDAO {

	public boolean insert(Connection conn, InsulinPenGlucoseEntity entity) throws SQLException {
		PreparedStatement ps = conn.prepareStatement(
				"insert into insulin_pen_glucose(sn,time,vlu,create_time) values(?,?,?,?)");
		ps.setString(1, entity.getSn());
		ps.setString(2, entity.getTime());
		ps.setString(3, entity.getVlu());
		ps.setTimestamp(4, new Timestamp(new Date().getTime()));

		boolean r = false;
		try {
			r = ps.executeUpdate() > 0;
		} catch(Exception e) {
			e.printStackTrace();
		}
		return r;
	}
	
	public InsulinPenGlucoseEntity getNewBySn(Connection conn, String sn) throws SQLException {
		PreparedStatement ps = conn.prepareStatement("select * from insulin_pen_glucose where sn=? order by create_time desc limit 1");
		ps.setString(1, sn);
		ResultSet rs = ps.executeQuery();
		if(rs.next()) {
			InsulinPenGlucoseEntity entity = new InsulinPenGlucoseEntity();
			entity.setSn(rs.getString("sn"));
			entity.setTime(DateUtil.parseStr(new Date(Long.parseLong(rs.getString("time"))), "yyyy-MM-dd HH:mm:ss"));
			entity.setVlu(rs.getString("vlu"));
			return entity;
		}
		return null;
	}
	
	public List<InsulinPenGlucoseEntity> getBySnAndTime(Connection conn, String sn, long start, long end) throws SQLException {
		List<InsulinPenGlucoseEntity> r = new ArrayList<>();
		PreparedStatement ps = conn.prepareStatement("select * from insulin_pen_glucose where sn=? and time>=? and time<=? order by create_time desc");
		ps.setString(1, sn);
		ps.setLong(2, start);
		ps.setLong(3, end);
		ResultSet rs = ps.executeQuery();
		while(rs.next()) {
			InsulinPenGlucoseEntity a = new InsulinPenGlucoseEntity();
			a.setSn(rs.getString("sn"));
			a.setTime(DateUtil.parseStr(new Date(Long.parseLong(rs.getString("time"))), "yyyy-MM-dd HH:mm:ss"));
			a.setVlu(rs.getString("vlu"));
			r.add(a);
		}
		return r;
	}
}
